package com.wing.cabinet.controller.app;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.request.UseInventoryKnifeForm;
import com.wing.cabinet.model.response.UseInventoryKnifeVO;
import com.wing.cabinet.model.response.UseInventoryProductVO;
import com.wing.cabinet.service.UseInventoryKnifeService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.setting.model.entity.SystemRuleInfo;
import com.wing.setting.service.SystemRuleInfoService;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 *
 * @author
 */
@Validated
@Api(value = "App-刀具在用库存管理", tags = "刀具在用库存管理")
@RestController("appUseInventoryKnifeController")
@RequestMapping("cabinet/app/useInventoryKnife")
@Slf4j
public class UseInventoryKnifeController {

    @Autowired
    private UseInventoryKnifeService useInventoryKnifeService;
    @Autowired
    private LocaleMessage localeMessage;
    
    @Autowired
    private SystemRuleInfoService systemRuleInfoService;

    @GetMapping()
    public PageResult<UseInventoryKnifeVO> list(
            @RequestParam(name = "page", value = "第几页", defaultValue = "1", required = false) Integer page
            ,@RequestParam(name = "limit", value = "每页多少条", defaultValue = "10", required = false) Integer limit
            ,@RequestParam(name = "sort", value="排序字段名", defaultValue = "create_time", required = false) String sort
            ,@RequestParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "desc", required = false) String order
    ) {
        Page<UseInventoryKnifeVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        Page<UseInventoryKnifeVO> list = useInventoryKnifeService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/storage/listIn")
    @ApiOperation(value = "存刀列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    public PageResult<UseInventoryKnifeVO> storageListIn(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "createTime") String sort
            ,@RequestParam(name = "order",defaultValue = "asc") String order
            ,String deviceCode
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String orderCode
            ,String labelCode
            ,String flag
            ,Long workOrderId
            ,Long creatorId
            ,String deviceCode4Query
            ,Long brandId
            ,Long processId
            ,String startCreateTime
            ,String endCreateTime
    ) {
        Page<UseInventoryProductVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
//        if (StringUtils.isBlank(sort)){
//            sort="labelCode";
//        }
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("queryFlag","useInventoryProduct4App");
        params.put("deviceCode",deviceCode);
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("deviceCode",deviceCode);
        params.put("orderCode",orderCode);
        params.put("parentLabelCode",labelCode);
        if (StringUtils.isNotBlank(flag)){
            params.put("flag",flag);
        }
        params.put("userId", JwtUtils.getLoginUserId());
        params.put("workOrderId",workOrderId);
        params.put("creator",creatorId);
        params.put("deviceCode4Query",deviceCode4Query);
        params.put("brandId",brandId);
        params.put("startCreateTime",startCreateTime);
        params.put("endCreateTime",endCreateTime);
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null&&systemRuleInfo.getAbFlag()!=null&&!systemRuleInfo.getAbFlag()){
            params.put("flag","user");
        }
        params.put("processId",processId);
        log.info("storage list in params:{}", JSON.toJSONString(params));
        Page<UseInventoryKnifeVO> list = useInventoryKnifeService.pageList4app(pg, params);
        if (StringUtils.isNotBlank(labelCode)){
            Collections.sort(list.getRecords());
        }
        //return new PageResult<>(orderByParentLabelCode(list.getRecords()), list.getTotal());
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    private List<UseInventoryKnifeVO> orderByParentLabelCode(List<UseInventoryKnifeVO> list){
        List<UseInventoryKnifeVO> resultList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)){
            UseInventoryKnifeVO preUseInventoryKnifeVO=list.get(0);
            String preParentLabelCode=preUseInventoryKnifeVO.getParentLabelCode();
            List<UseInventoryKnifeVO> tempList=new ArrayList<>();
            tempList.add(preUseInventoryKnifeVO);
            for (int i=1;i<list.size();i++){
                UseInventoryKnifeVO next=list.get(i);
                if (next.getParentLabelCode()!=null&&next.getParentLabelCode().equals(preParentLabelCode)){
                    tempList.add(next);
                }else{
                    if (tempList.size()>1){
                        UseInventoryKnifeVO useInventoryKnifeVO=new UseInventoryKnifeVO();
                        BeanUtils.copyProperties(tempList.get(0),useInventoryKnifeVO);
                        useInventoryKnifeVO.setLabelCode(useInventoryKnifeVO.getParentLabelCode());
                        useInventoryKnifeVO.setDetailList(tempList);
                        resultList.add(useInventoryKnifeVO);

                    }else{
                        resultList.add(preUseInventoryKnifeVO);
                    }
                    tempList=new ArrayList<>();
                    tempList.add(next);
                    preParentLabelCode=next.getParentLabelCode();
                }
                preUseInventoryKnifeVO=next;
            }
            if (tempList.size()>1){
                UseInventoryKnifeVO useInventoryKnifeVO=new UseInventoryKnifeVO();
                BeanUtils.copyProperties(tempList.get(0),useInventoryKnifeVO);
                useInventoryKnifeVO.setLabelCode(useInventoryKnifeVO.getParentLabelCode());
                useInventoryKnifeVO.setDetailList(tempList);
                resultList.add(useInventoryKnifeVO);

            }else{
                resultList.add(preUseInventoryKnifeVO);
            }
        }

        return resultList;
    }


    @GetMapping("/repair/listIn")
    @ApiOperation(value = "存维修刀列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    public PageResult<UseInventoryKnifeVO> repairtListIn(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "createTime") String sort
            ,@RequestParam(name = "order",defaultValue = "asc") String order
            ,String deviceCode
            ,String cabCodes
            ,Long productCategoryId
            ,Long productTypeId
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String orderCode
            ,String labelCode
            ,String flag
            ,Long workOrderId
            ,Long creatorId
            ,String deviceCode4Query
            ,Long brandId
            ,Long processId
            ,String startCreateTime
            ,String endCreateTime

    ) {
        Page<UseInventoryProductVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
//        if (StringUtils.isBlank(sort)){
//            sort="labelCode";
//        }
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("deviceCode",deviceCode);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",Arrays.asList(cabCodeArray));
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("deviceCode",deviceCode);
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        params.put("queryFlag","useInventoryProduct4App");
        params.put("orderCode",orderCode);
        params.put("parentLabelCode",labelCode);
        if (StringUtils.isNotBlank(flag)){
            params.put("flag",flag);
        }
        params.put("userId", JwtUtils.getLoginUserId());
        params.put("workOrderId",workOrderId);
        params.put("creator",creatorId);
        params.put("deviceCode4Query",deviceCode4Query);
        params.put("brandId",brandId);
        params.put("processId",processId);
        params.put("startCreateTime",startCreateTime);
        params.put("endCreateTime",endCreateTime);
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null&&systemRuleInfo.getAbFlag()!=null&&!systemRuleInfo.getAbFlag()){
            params.put("flag","user");
        }
        log.info("repair list in params:{}", JSON.toJSONString(params));
        Page<UseInventoryKnifeVO> list = useInventoryKnifeService.pageList4app(pg, params);
        if (StringUtils.isNotBlank(labelCode)){
            Collections.sort(list.getRecords());
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
        //return new PageResult<>(orderByParentLabelCode(list.getRecords()), list.getTotal());
    }

    @GetMapping("/recycle/listIn")
    @ApiOperation(value = "存报废刀列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    public PageResult<UseInventoryKnifeVO> recycleListIn(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "id") String sort
            ,@RequestParam(name = "order",defaultValue = "asc") String order
            ,String deviceCode
            ,String cabCodes
            ,Long productCategoryId
            ,Long productTypeId
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String orderCode
            ,String labelCode
            ,String flag
            ,Long workOrderId
            ,Long creatorId
            ,String deviceCode4Query
            ,Long brandId
            ,Long processId
            ,String startCreateTime
            ,String endCreateTime
    ) {
        Page<UseInventoryProductVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
//        if (StringUtils.isBlank(sort)){
//            sort="labelCode";
//        }
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("queryFlag","useInventoryProduct4App");
        params.put("deviceCode",deviceCode);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("deviceCode",deviceCode);
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        params.put("orderCode",orderCode);
        params.put("parentLabelCode",labelCode);
        if (StringUtils.isNotBlank(flag)){
            params.put("flag",flag);
        }
        params.put("userId", JwtUtils.getLoginUserId());
        params.put("workOrderId",workOrderId);
        params.put("creator",creatorId);
        params.put("deviceCode4Query",deviceCode);
        params.put("brandId",brandId);
        params.put("processId",processId);
        params.put("startCreateTime",startCreateTime);
        params.put("endCreateTime",endCreateTime);
//        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getOne(new QueryWrapper<SystemRuleInfo>());
        SystemRuleInfo systemRuleInfo=systemRuleInfoService.getRuleInfo();
        if (systemRuleInfo!=null&&systemRuleInfo.getAbFlag()!=null&&!systemRuleInfo.getAbFlag()){
            params.put("flag","user");
        }
        log.info("recycle list in params:{}", JSON.toJSONString(params));
        Page<UseInventoryKnifeVO> list = useInventoryKnifeService.pageList4app(pg, params);
        if (StringUtils.isNotBlank(labelCode)){
            Collections.sort(list.getRecords());
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
        //return new PageResult<>(orderByParentLabelCode(list.getRecords()), list.getTotal());
    }

    @GetMapping("/detail/{id}")
    public JsonResult detail(@PathVariable("id") Long useInventoryKnifeId) {
        UseInventoryKnifeVO useInventoryKnifeVO = useInventoryKnifeService.get4appById(useInventoryKnifeId);
        if (useInventoryKnifeVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), useInventoryKnifeVO);
    }

    @PostMapping()
    public JsonResult add(@Validated UseInventoryKnifeForm useInventoryKnifeForm) {
        if (useInventoryKnifeService.add(useInventoryKnifeForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

}
